import Router from 'koa-router';
import { pool } from '../../config/database';
import { authMiddleware } from '../../middleware/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { ApiResponse, Order, OrderCreateInput, OrderUpdateInput, OrderQueryParams, JwtPayload } from '../../types';

const router = new Router({ prefix: '/api/orders' });

// 获取订单列表（管理员可以看所有订单，用户只能看自己的）
router.get('/', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { 
      page = 1, 
      limit = 10, 
      status, 
      start_date, 
      end_date 
    } = ctx.query as OrderQueryParams;
    
    const offset = (Number(page) - 1) * Number(limit);
    
    let whereClause = 'WHERE 1=1';
    const params: any[] = [];
    
    // 非管理员只能看自己的订单
    if (user.email !== 'admin@example.com') {
      whereClause += ' AND o.user_id = ?';
      params.push(user.id);
    }
    
    if (status) {
      whereClause += ' AND o.status = ?';
      params.push(status);
    }
    
    if (start_date) {
      whereClause += ' AND o.created_at >= ?';
      params.push(start_date);
    }
    
    if (end_date) {
      whereClause += ' AND o.created_at <= ?';
      params.push(end_date + ' 23:59:59');
    }
    
    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM orders o ${whereClause}`,
      params
    ) as [RowDataPacket[], any];
    const total = countResult[0].total;
    
    // 获取订单列表
    const [orders] = await pool.execute(
      `SELECT o.*, 
              u.username, u.nickname, u.email as user_email,
              p.name as config_name, p.price as config_price
       FROM orders o
       LEFT JOIN users u ON o.user_id = u.id
       LEFT JOIN products p ON o.config_id = p.id
       ${whereClause} 
       ORDER BY o.created_at DESC 
       LIMIT ? OFFSET ?`,
      [...params, Number(limit), offset]
    ) as [RowDataPacket[], any];
    
    ctx.body = {
      success: true,
      data: orders,
      meta: {
        total,
        page: Number(page),
        limit: Number(limit),
        totalPages: Math.ceil(total / Number(limit))
      }
    } as ApiResponse<Order[]>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取订单列表失败：' + error.message
    } as ApiResponse;
  }
});

// 获取我的订单
router.get('/my', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { page = 1, limit = 10, status } = ctx.query;
    const offset = (Number(page) - 1) * Number(limit);
    
    let whereClause = 'WHERE o.user_id = ?';
    const countParams: any[] = [user.id];
    const queryParams: any[] = [user.id];
    
    if (status) {
      whereClause += ' AND o.status = ?';
      countParams.push(status);
      queryParams.push(status);
    }
    
    // 添加分页参数
    queryParams.push(Number(limit), offset);
    
    // 获取总数
    const [countResult] = await pool.query(
      `SELECT COUNT(*) as total FROM orders o ${whereClause}`,
      countParams
    ) as [RowDataPacket[], any];
    const total = countResult[0].total;
    
    // 获取订单列表
    const [orders] = await pool.query(
      `SELECT o.*, 
              p.name as config_name, p.price as config_price, p.specifications as config_specs, 
              p.images as config_images, p.warranty as config_warranty
       FROM orders o
       LEFT JOIN products p ON o.config_id = p.id
       ${whereClause} 
       ORDER BY o.created_at DESC 
       LIMIT ? OFFSET ?`,
      queryParams
    ) as [RowDataPacket[], any];

    ctx.body = {
      success: true,
      data: orders,
      meta: {
        total,
        page: Number(page),
        limit: Number(limit),
        totalPages: Math.ceil(total / Number(limit))
      }
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取我的订单失败：' + error.message
    } as ApiResponse;
  }
});

// 获取订单详情
router.get('/:id', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    
    const [orders] = await pool.execute(
      `SELECT o.*, 
              u.username, u.nickname, u.email as user_email,
              p.name as config_name, p.price as config_price, p.specifications as config_specs, 
              p.images as config_images, p.warranty as config_warranty
       FROM orders o
       LEFT JOIN users u ON o.user_id = u.id
       LEFT JOIN products p ON o.config_id = p.id
       WHERE o.id = ?`,
      [id]
    ) as [RowDataPacket[], any];
    
    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '订单不存在'
      } as ApiResponse;
      return;
    }
    
    const order = orders[0];
    
    // 检查权限（只有订单所有者或管理员可以查看）
    if (order.user_id !== user.id && user.email !== 'admin@example.com') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限查看此订单'
      } as ApiResponse;
      return;
    }
    
    ctx.body = {
      success: true,
      data: order
    } as ApiResponse<Order>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取订单详情失败：' + error.message
    } as ApiResponse;
  }
});

// 通过订单号获取订单详情
router.get('/no/:orderNo', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { orderNo } = ctx.params;
    
    const [orders] = await pool.execute(
      `SELECT o.*, 
              u.username, u.nickname, u.email as user_email,
              p.name as config_name, p.price as config_price, p.specifications as config_specs, 
              p.images as config_images, p.warranty as config_warranty
       FROM orders o
       LEFT JOIN users u ON o.user_id = u.id
       LEFT JOIN products p ON o.config_id = p.id
       WHERE o.order_no = ?`,
      [orderNo]
    ) as [RowDataPacket[], any];
    
    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '订单不存在'
      } as ApiResponse;
      return;
    }
    
    const order = orders[0];
    
    // 检查权限
    if (order.user_id !== user.id && user.email !== 'admin@example.com') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限查看此订单'
      } as ApiResponse;
      return;
    }
    
    ctx.body = {
      success: true,
      data: order
    } as ApiResponse<Order>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取订单详情失败：' + error.message
    } as ApiResponse;
  }
});

// 创建订单
router.post('/', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const {
      config_id,
      product_id,
      product_type = 'config', // 默认为配置类型
      merchant_id = 1, // 默认商户ID为1
      quantity = 1,
      unit_price, // 可选，如果没有提供则使用产品价格
      shipping_fee = 0, // 运费，默认0
      discount_amount = 0, // 折扣金额，默认0
      payment_method = 'online', // 支付方式，默认在线支付
      shipping_address,
      notes,
      remark
    } = ctx.request.body as OrderCreateInput;
    
    // 验证必填字段
    if ((!config_id && !product_id) || !shipping_address) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '缺少必填字段（产品ID或配置ID、收货地址）'
      } as ApiResponse;
      return;
    }

    // 确定使用的产品ID
    const productId = product_type === 'config' ? config_id : product_id;
    
    // 验证产品是否存在且有库存
    const [products] = await pool.execute(
      'SELECT * FROM products WHERE id = ?',
      [productId]
    ) as [RowDataPacket[], any];
    
    if (products.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '产品不存在'
      } as ApiResponse;
      return;
    }
    
    const product = products[0];
    
    if (product.stock < quantity) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '库存不足'
      } as ApiResponse;
      return;
    }
    
    // 计算价格
    const unitPrice = unit_price || product.price; // 优先使用传入的单价，否则使用产品价格
    const totalPrice = unitPrice * quantity; // 商品总价
    const actualShippingFee = shipping_fee || 0; // 实际运费
    const actualDiscountAmount = discount_amount || 0; // 实际折扣金额
    const finalPrice = totalPrice + actualShippingFee - actualDiscountAmount; // 最终价格
    
    // 生成订单号
    const orderNo = `ORDER${Date.now()}${Math.random().toString(36).substr(2, 9).toUpperCase()}`;
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 创建订单
      const [result] = await connection.execute(
        `INSERT INTO orders (
          order_no, user_id, product_type, product_id, config_id, merchant_id, 
          quantity, unit_price, total_price, shipping_fee, discount_amount, 
          final_price, status, payment_method, payment_status, shipping_address, 
          notes, remark
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          orderNo,
          user.id,
          product_type,
          product_type === 'product' ? productId : null, // product_id
          product_type === 'config' ? productId : null, // config_id
          merchant_id,
          quantity,
          unitPrice,
          totalPrice,
          actualShippingFee,
          actualDiscountAmount,
          finalPrice,
          'pending', // 默认状态
          payment_method,
          'pending', // 默认支付状态
          JSON.stringify(shipping_address),
          notes || null,
          remark || null
        ]
      ) as [ResultSetHeader, any];
      
      // 更新库存和销量
      await connection.execute(
        'UPDATE products SET stock = stock - ?, sales = sales + ? WHERE id = ?',
        [quantity, quantity, productId]
      );
      
      await connection.commit();
      connection.release();
      
      // 获取创建的订单信息
      const [orders] = await pool.execute(
        `SELECT o.*, 
                p.name as config_name, p.price as config_price
         FROM orders o
         LEFT JOIN products p ON o.config_id = p.id
         WHERE o.id = ?`,
        [result.insertId]
      ) as [RowDataPacket[], any];
      
      const order = orders[0] as Order;
      
      ctx.body = {
        success: true,
        data: order,
        message: '订单创建成功'
      } as ApiResponse<Order>;
    } catch (error) {
      await connection.rollback();
      connection.release();
      throw error;
    }
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '创建订单失败：' + error.message
    } as ApiResponse;
  }
});

// 取消订单
router.patch('/:id/cancel', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    const { reason } = ctx.request.body as { reason?: string };
    
    const [orders] = await pool.execute(
      'SELECT * FROM orders WHERE id = ? AND user_id = ?',
      [id, user.id]
    ) as [RowDataPacket[], any];
    
    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '订单不存在或无权限'
      } as ApiResponse;
      return;
    }
    
    const order = orders[0];
    
    if (order.status !== 'pending') {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '只能取消待处理的订单'
      } as ApiResponse;
      return;
    }
    
    // 更新订单状态为取消
    await pool.execute(
      'UPDATE orders SET status = ?, cancel_reason = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      ['cancelled', reason, id]
    );
    
    // 恢复库存
    await pool.execute(
      'UPDATE products SET stock = stock + ? WHERE id = ?',
      [order.quantity, order.config_id]
    );
    
    ctx.body = {
      success: true,
      message: '订单取消成功'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '取消订单失败：' + error.message
    } as ApiResponse;
  }
});

// 确认收货
router.patch('/:id/confirm', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    
    const [orders] = await pool.execute(
      'SELECT * FROM orders WHERE id = ? AND user_id = ?',
      [id, user.id]
    ) as [RowDataPacket[], any];
    
    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '订单不存在或无权限'
      } as ApiResponse;
      return;
    }
    
    const order = orders[0];
    
    if (order.status !== 'shipped') {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '只能确认已发货的订单'
      } as ApiResponse;
      return;
    }
    
    await pool.execute(
      'UPDATE orders SET status = ?, delivered_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      ['delivered', id]
    );
    
    ctx.body = {
      success: true,
      message: '确认收货成功'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '确认收货失败：' + error.message
    } as ApiResponse;
  }
});

// 申请退款
router.patch('/:id/refund', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    const { reason } = ctx.request.body as { reason: string };
    
    const [orders] = await pool.execute(
      'SELECT * FROM orders WHERE id = ? AND user_id = ?',
      [id, user.id]
    ) as [RowDataPacket[], any];
    
    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '订单不存在或无权限'
      } as ApiResponse;
      return;
    }
    
    const order = orders[0];
    
    if (!['delivered', 'shipped'].includes(order.status)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '只能对已发货或已送达的订单申请退款'
      } as ApiResponse;
      return;
    }
    
    await pool.execute(
      'UPDATE orders SET status = ?, refund_reason = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      ['refund_requested', reason, id]
    );
    
    ctx.body = {
      success: true,
      message: '退款申请已提交'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '申请退款失败：' + error.message
    } as ApiResponse;
  }
});

// 更新收货地址
router.patch('/:id/address', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    const addressData = ctx.request.body;
    
    const [orders] = await pool.execute(
      'SELECT * FROM orders WHERE id = ? AND user_id = ?',
      [id, user.id]
    ) as [RowDataPacket[], any];
    
    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '订单不存在或无权限'
      } as ApiResponse;
      return;
    }
    
    const order = orders[0];
    
    if (!['pending', 'confirmed'].includes(order.status)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '只能修改待处理或已确认订单的收货地址'
      } as ApiResponse;
      return;
    }
    
    await pool.execute(
      'UPDATE orders SET shipping_address = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [JSON.stringify(addressData), id]
    );
    
    ctx.body = {
      success: true,
      message: '收货地址更新成功'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '更新收货地址失败：' + error.message
    } as ApiResponse;
  }
});

// 添加订单备注
router.patch('/:id/note', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    const { note } = ctx.request.body as { note: string };
    
    const [orders] = await pool.execute(
      'SELECT * FROM orders WHERE id = ? AND user_id = ?',
      [id, user.id]
    ) as [RowDataPacket[], any];
    
    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '订单不存在或无权限'
      } as ApiResponse;
      return;
    }
    
    await pool.execute(
      'UPDATE orders SET notes = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [note, id]
    );
    
    ctx.body = {
      success: true,
      message: '备注添加成功'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '添加备注失败：' + error.message
    } as ApiResponse;
  }
});

// 更新订单状态（管理员功能）
router.put('/:id', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    const { status, notes } = ctx.request.body as OrderUpdateInput;
    
    // 检查管理员权限
    if (user.email !== 'admin@example.com') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限修改订单状态'
      } as ApiResponse;
      return;
    }
    
    // 检查订单是否存在
    const [orders] = await pool.execute(
      'SELECT * FROM orders WHERE id = ?',
      [id]
    ) as [RowDataPacket[], any];
    
    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '订单不存在'
      } as ApiResponse;
      return;
    }
    
    const order = orders[0];
    
    // 构建更新字段
    const updateFields: string[] = [];
    const updateValues: any[] = [];
    
    if (status !== undefined) {
      updateFields.push('status = ?');
      updateValues.push(status);
    }
    
    if (notes !== undefined) {
      updateFields.push('notes = ?');
      updateValues.push(notes);
    }
    
    if (updateFields.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '没有要更新的字段'
      } as ApiResponse;
      return;
    }
    
    updateValues.push(id);
    
    // 如果是取消订单，需要恢复库存
    if (status === 'cancelled' && order.status !== 'cancelled') {
      const connection = await pool.getConnection();
      await connection.beginTransaction();
      
      try {
        // 更新订单状态
        await connection.execute(
          `UPDATE orders SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
          updateValues
        );
        
        // 恢复库存和销量
        await connection.execute(
          'UPDATE products SET stock = stock + ?, sales = sales - ? WHERE id = ?',
          [order.quantity, order.quantity, order.config_id]
        );
        
        await connection.commit();
        connection.release();
      } catch (error) {
        await connection.rollback();
        connection.release();
        throw error;
      }
    } else {
      // 普通更新
      await pool.execute(
        `UPDATE orders SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
        updateValues
      );
    }
    
    // 获取更新后的订单信息
    const [updatedOrders] = await pool.execute(
      `SELECT o.*, 
              p.name as config_name, p.price as config_price
       FROM orders o
       LEFT JOIN products p ON o.config_id = p.id
       WHERE o.id = ?`,
      [id]
    ) as [RowDataPacket[], any];
    
    const updatedOrder = updatedOrders[0] as Order;
    
    ctx.body = {
      success: true,
      data: updatedOrder,
      message: '订单状态更新成功'
    } as ApiResponse<Order>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '更新订单状态失败：' + error.message
    } as ApiResponse;
  }
});

// 删除订单（管理员功能）
router.delete('/:id', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { id } = ctx.params;
    
    // 检查管理员权限
    if (user.email !== 'admin@example.com') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限删除订单'
      } as ApiResponse;
      return;
    }
    
    // 检查订单是否存在
    const [orders] = await pool.execute(
      'SELECT * FROM orders WHERE id = ?',
      [id]
    ) as [RowDataPacket[], any];
    
    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '订单不存在'
      } as ApiResponse;
      return;
    }
    
    const order = orders[0];
    
    // 如果订单未取消，需要恢复库存
    if (order.status !== 'cancelled') {
      const connection = await pool.getConnection();
      await connection.beginTransaction();
      
      try {
        // 删除订单
        await connection.execute(
          'DELETE FROM orders WHERE id = ?',
          [id]
        );
        
        // 恢复库存和销量
        await connection.execute(
          'UPDATE products SET stock = stock + ?, sales = sales - ? WHERE id = ?',
          [order.quantity, order.quantity, order.config_id]
        );
        
        await connection.commit();
        connection.release();
      } catch (error) {
        await connection.rollback();
        connection.release();
        throw error;
      }
    } else {
      // 直接删除已取消的订单
      await pool.execute(
        'DELETE FROM orders WHERE id = ?',
        [id]
      );
    }
    
    ctx.body = {
      success: true,
      message: '订单删除成功'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '删除订单失败：' + error.message
    } as ApiResponse;
  }
});

export default router; 